package xyz.poke.business.tool.utils;

import cn.hutool.core.util.ObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author 迫壳
 * @date 2024/3/23 10:12
 */
@Component
public class RedisUtils {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 删除单个key
     * @param key
     * @return
     */
    public Boolean del(String key){
        return redisTemplate.delete(key);
    }

    /**
     * 删除多个keys
     * @param keys
     * @return
     */
    public Boolean delKeys(List<String> keys){
        Long resultCount = redisTemplate.delete(keys);
        return !ObjectUtil.isNull(resultCount) && resultCount > 0;
    }

    /**
     * 指定key 设置过期时间
     * @param key
     * @param time
     */
    public Boolean expire(String key,long time){
        return redisTemplate.expire(key,time, TimeUnit.MINUTES);
    }

    /**
     * 根据key获取过期时间
     * @param key
     * @return
     */
    public Long getExpire(String key){
        return redisTemplate.getExpire(key);
    }

    /**
     * 判断key是否存在
     * @param key
     * @return
     */
    public boolean hasKey(String key){
        return Boolean.TRUE.equals(redisTemplate.hasKey(key));
    }

    /**
     * 设置永久键
     */
    public void set(String key, Object value){
        redisTemplate.boundValueOps(key).set(value);
    }

    /**
     * 设置值，并按照分钟设置过期时间
     * @param key
     * @param value
     * @param time
     */
    public void setEx(String key, Object value, Long time){
        redisTemplate.boundValueOps(key).set(value, time, TimeUnit.MINUTES);
    }

    /**
     *
     * @param key
     * @return
     */
    public Long increment(String key, Long v){
        return redisTemplate.boundValueOps(key).increment(v);
    }

    /**
     * 根据key值获取value
     * @param key
     * @return
     */
    public Object get(String key){
        return redisTemplate.boundValueOps(key).get();
    }
}
